package src.project.jumble;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.view.Menu;
import android.view.MenuItem;

public class Jumble extends Activity implements SharedPreferences.OnSharedPreferenceChangeListener{
    /** Called when the activity is first created. */
	
	private LinearLayout _layout;
	private List<String> words;
	private List<LetterTile> tiles;
	private int wordIndex;
	private SharedPreferences preferences;
	private String dif;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("dif", "Easy");
        editor.commit();
        
        preferences.registerOnSharedPreferenceChangeListener(this);
        
        dif = preferences.getString("dif", "Easy");
        Log.v("Difficulty", dif);
        
        _layout = (LinearLayout) findViewById(R.id.LinearLayout01);
        _layout.setGravity(Gravity.CENTER);
        
        words = new ArrayList<String>();
        LoadWords();

    }
    
    private void LoadWords() {
        InputStream stream = getResources().openRawResource(R.raw.words);
        
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        
        try {
			while(reader.ready()){
				String str = reader.readLine();
				words.add(str);

			}
		} catch (IOException e) {
			Toast.makeText(this, "Unable to load word file: " + e.getMessage(), Toast.LENGTH_LONG).show();
			words.add("s");
		}
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu){
    	MenuInflater inflator = getMenuInflater();
    	inflator.inflate(R.menu.menu, menu);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	switch(item.getItemId()){
    	case R.id.Preferences:
    		Intent i = new Intent(this, Preferences.class);
    		startActivity(i);
    		break;
    	}
    	return true;
    }
    
	private void Begin() {
		Random r = new Random();
		wordIndex = r.nextInt(words.size());
		
        char[] wordArray = words.get(wordIndex).toCharArray();
		int length = wordArray.length;
		if(dif.equalsIgnoreCase("easy"))
		{
			if(length < 5)
				Load(wordArray);
			else
				Begin();
			
		}
		else if(dif.equalsIgnoreCase("medium"))
		{
			if(length < 7 && length >= 5)
				Load(wordArray);
			else
				Begin();
		}
		else if(dif.equalsIgnoreCase("hard"))
		{
			if(length < 9 && length >= 7)
				Load(wordArray);
			else
				Begin();
		}
		else if(dif.equalsIgnoreCase("very hard"))
		{
			if(length >= 9)
				Load(wordArray);
			else
				Begin();
		}
	}  

	private void Load(char[] wordArray) {
		List<String> charList = new ArrayList<String>();
        tiles = new ArrayList<LetterTile>();
        for(char c: wordArray)
        	charList.add(String.valueOf(c));
        Collections.shuffle(charList);
        
        for(String s : charList){
        	LetterTile t = new LetterTile(this, s);
        	tiles.add(t);
        	_layout.addView(t);
    	}
	}

	public void ButtonMoved(LetterTile tile) {
		int index = tiles.indexOf(tile);
		
		if(tile.GetX() < 0)
		{
			int spaceOver = (int)Math.abs(tile.GetX()/tile.WIDTH) + 1;
			if(index - spaceOver < 0)
				return;
			else{
				Swap(tiles.get(index), tiles.get(index-spaceOver));
				
				Toast.makeText(this,"Swapping " + tile.GetLetter() + 
						" and " +tiles.get(index-spaceOver).GetLetter(),Toast.LENGTH_SHORT)
						.show();
				
				CheckForWin();
			}
		}
		
		else if(tile.GetX() > tile.WIDTH)
		{
			int spaceOver = (int)Math.abs(tile.GetX()/tile.WIDTH);
			if(index + spaceOver > tiles.size())
				return;
			else{
				Swap(tiles.get(index), tiles.get(index + spaceOver));
				
				Toast.makeText(this,"Swapping " + tile.GetLetter() + 
						" and " +tiles.get(index+spaceOver).GetLetter(),Toast.LENGTH_SHORT)
						.show();
				
				CheckForWin();

			}
		}
	}

	private void Swap(LetterTile thisTile, LetterTile thatTile) {
		
		String thisLetter = thisTile.GetLetter();
		String thatLetter = thatTile.GetLetter();
		
		thisTile.SetLetter(thatLetter);
		thatTile.SetLetter(thisLetter);
		
	}
	
	private void CheckForWin()
	{
		String s = "";
		
		for(LetterTile t : tiles)
			s += t.GetLetter();
		
		if(s.equals(words.get(wordIndex)))
			Toast.makeText(this,"Congratulations.You Won!",Color.GRAY).show();
	}
	
	public void NewOnClick(View view)
	{
		if (_layout.getChildCount() > 0){
			_layout.removeAllViews();
			tiles.clear();
		}
		Begin();
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		
		dif = sharedPreferences.getString(key, "NULL");
		Log.v("Dif", dif);
		
		if (_layout.getChildCount() > 0)
		{
			_layout.removeAllViews();
			tiles.clear();
		}
		Begin();		
	}
}